package com.onlineproject.action;


import java.awt.Color;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import javax.jms.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;

import com.onlineproject.model.*;
import com.onlineproject.util.SendEmail;
import com.onlineproject.dao.*;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;

import org.apache.struts2.ServletActionContext;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


public class LoginRegisterAction extends ActionSupport{
	private StudentDao studentDao;
	
	
	private TeacherDao teacherDao;
	
	private String name;
	private String email;
	private String password;
	private String usertype;
	//鎺ュ彈浠庢敞鍐屾垨鐧诲綍鐣岄潰浼犺繃鏉ョ殑楠岃瘉鐮�
	private String safeCode;
	//婵�椿鏃舵帴鍙椾粠閭閾炬帴涓紶杩囨潵鐨勬縺娲荤爜
	private String activateCode;
	public String getActivateCode() {
		return activateCode;
	}

	public void setActivateCode(String activateCode) {
		this.activateCode = activateCode;
	}

	public String getSafeCode() {
		return safeCode;
	}

	public void setSafeCode(String safeCode) {
		this.safeCode = safeCode;
	}

	public String getName(){
		return name;
	}
	
	public String getEmail(){
		return email;
	}
	
	public String getPassword(){
		return password;
	}
	
	public void setName(String name){
		this.name = name;
	}
	
	public void setEmail(String email){
		this.email = email;
	}
	public void setPassword(String password){
		this.password = password;
	}
	
	/*public LoginRegisterAction(){
		ClassPathResource resource = new ClassPathResource("applicationContext.xml");
		XmlBeanFactory factory = new XmlBeanFactory(resource);
	    studentDao = (StudentDao)factory.getBean("studentDao");
	    teacherDao = (TeacherDao)factory.getBean("teacherDao");
	}*/

	public String exit()
	{
		ActionContext.getContext().getSession().clear();
		return "exit";
	}
	
	 public String adminLoginCheck(){
		 String yanZhengMa = (String)ServletActionContext.getRequest().getSession().getAttribute("rand");
			if(yanZhengMa==null | (!yanZhengMa.equals(safeCode)))
				return "failure";		 
		 try{
                 if("admin".equals(getEmail())){       //鹿脺脌铆脭卤碌脟脗陆
                               Teacher admin = teacherDao.findById(getEmail());
                               
                               if(admin != null && getPassword().equals(admin.getPassword())){
                                       ActionContext.getContext().getSession().put("usertype", "admin");
//                             
                               if( admin.getLastTime() != null)
                                       ActionContext.getContext().getSession().put("lastlogintime", admin.getLastTime().toString().substring(0,19));//卤拢麓忙脡脧麓脦碌脟脗录脢卤录盲
                               else
                                       ActionContext.getContext().getSession().put("lastlogintime", new Date().toString().substring(0,19));//卤拢麓忙脡脧麓脦碌脟脗录脢卤录盲
                               
                                       SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                                     
                                       admin.setLastTime(new Date());//卤拢麓忙碌脟脗录脢卤录盲
                               teacherDao.update(admin);       //赂眉脨脗碌脟脗录脢卤录盲          
                               return "success_admin";
                               }               
                               return "failure";
                       }
                 return "failure";
               }catch(Exception e){
                       e.printStackTrace();
                       return "failure";
               }
       
}
					
	public String loginCheck(){
		String yanZhengMa = (String)ServletActionContext.getRequest().getSession().getAttribute("rand");
		if(yanZhengMa==null | (!yanZhengMa.equals(safeCode)))
			return "failure";
		
	  try{
			//鍒ゆ柇鐧诲綍绫诲瀷锛�锛氬鐢�  2锛氳�甯�    3锛氭父瀹�
			if(getUsertype()!= null && getUsertype().equals("1"))//学生
			{
				Student stu = studentDao.findById(getEmail());
				
				if(!stu.getActivateCode().equals("0"))//激活验证
					return "failure";
		
				if(stu != null && getPassword().equals(stu.getPassword())){//楠岃瘉瀵嗙爜
					ServletActionContext.getRequest().setAttribute("stu", stu);
					ActionContext.getContext().getSession().put("studentId", getEmail());
					ActionContext.getContext().getSession().put("usertype", "student");
					if(stu.getLastTime() != null)
						ActionContext.getContext().getSession().put("lastlogintime", stu.getLastTime().toString().substring(0,19));//淇濆瓨涓婃鐧诲綍鏃堕棿
					else
						ActionContext.getContext().getSession().put("lastlogintime", new Date().toString().substring(0,19));//淇濆瓨褰撳墠鏃堕棿
						
					SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

					//stu.setLastTime(new Date());//淇濆瓨鐧诲綍鏃堕棿

					Date date = time.parse(time.format(new Date()));
					stu.setLastTime(date);//淇濆瓨鐧诲綍鏃堕棿

			      	studentDao.update(stu);	//鏇存柊鐧诲綍鏃堕棿	
			      	if(stu.getName() == null || stu.getName().trim().equals(""))
			      		return "fill_student";
			      	else
			      		return "success_student";
				}
					return "failure";				
			}else if(getUsertype()!= null && getUsertype().equals("2")){//鑰佸笀鐧诲綍
				if("admin".equals(getEmail())){	//绠＄悊鍛樼櫥闄�
					Teacher admin = teacherDao.findById(getEmail());
					
					if(admin != null && getPassword().equals(admin.getPassword())){
						ActionContext.getContext().getSession().put("usertype", "admin");
					
					if( admin.getLastTime() != null)
						ActionContext.getContext().getSession().put("lastlogintime", admin.getLastTime().toString().substring(0,19));//淇濆瓨涓婃鐧诲綍鏃堕棿
					else
						ActionContext.getContext().getSession().put("lastlogintime", new Date().toString().substring(0,19));//淇濆瓨涓婃鐧诲綍鏃堕棿
					
						SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

						
						//admin.setLastTime(new Date());//淇濆瓨鐧诲綍鏃堕棿

						Date date = time.parse(time.format(new Date()));
						admin.setLastTime(date);//淇濆瓨鐧诲綍鏃堕棿

				     	teacherDao.update(admin);	//鏇存柊鐧诲綍鏃堕棿		
				     	return "success_admin";
					}		
					return "failure";
				}
				
				
				Teacher tch = teacherDao.findById(getEmail());
				
				if(!tch.getActivateCode().equals("0"))//激活验证
					return "failure";
				
				if(tch != null && getPassword().equals(tch.getPassword())){
					//ServletActionContext.getRequest().setAttribute("tch", tch);
					ActionContext.getContext().getSession().put("teacherId", tch.getEmail());
					ActionContext.getContext().getSession().put("usertype", "teacher");
					if(tch.getLastTime() != null)
						ActionContext.getContext().getSession().put("lastlogintime", tch.getLastTime().toString().substring(0,19));//淇濆瓨涓婃鐧诲綍鏃堕棿
					else
						ActionContext.getContext().getSession().put("lastlogintime", new Date().toString().substring(0,19));//淇濆瓨褰撳墠鏃堕棿
						
					SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

					//tch.setLastTime(new Date());//淇濆瓨鐧诲綍鏃堕棿

					Date date = time.parse(time.format(new Date()));
					
					tch.setLastTime(date);//淇濆瓨鐧诲綍鏃堕棿

			     	teacherDao.update(tch);	//鏇存柊鐧诲綍鏃堕棿	
			     	
			     	if(tch.getName() == null || tch.getName().trim().equals(""))
			     		return "fill_teacher";
			     	else
			     		return "success_teacher";
				}				
				return "failure";
			}
			return "failure";
		}catch(Exception e){
			e.printStackTrace();
			return "failure";
		}
	}
	
	/*
	 * 
	 * 鏍规嵁session涓殑studentId灏唖tudent瀵硅薄stu鍔犺浇鍒皉equest
	 */
	public void  getStudentRequest(){
		try{
			Student stu=(Student)studentDao.findById((String)ActionContext.getContext().getSession().get("studentId"));
			
			if(stu !=null)
				ServletActionContext.getRequest().setAttribute("stu", stu);
				
		}catch(Exception e){
			e.printStackTrace();			
		}		
	}
	
	/*
	 * 
	 * 鏍规嵁session涓殑teacherId灏唗eacher瀵硅薄tch鍔犺浇鍒皉equest
	 */
	public void  getTeacherRequest(){
		try{
			Teacher tch=(Teacher)teacherDao.findById((String)ActionContext.getContext().getSession().get("teacherId"));
			
			if(tch !=null)
				ServletActionContext.getRequest().setAttribute("tch", tch);
				
		}catch(Exception e){
			e.printStackTrace();			
		}		
	}
	
	public String register(){
		String yanZhengMa = (String)ServletActionContext.getRequest().getSession().getAttribute("rand");
		if(yanZhengMa==null | (!yanZhengMa.equals(safeCode)))
			return "failure";
		if(getUsertype()!= null && getUsertype().equals("1"))//学生
		{
			//杩欓噷涓嶇敤鏂规硶getEmail()锛岀洿鎺ョ敤灞炴�email鍗冲彲
			Student stu =new Student(getEmail(),getPassword());
	
			try{			

				SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");		
				Date date=time.parse(time.format(new Date()));
				stu.setRegisterTime(new Date());//淇濆瓨娉ㄥ唽鏃堕棿
				time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				stu.setLastTime(new Date());//淇濆瓨涓婃鐧诲綍鏃堕棿
				String activateCode = getRandomString();
				stu.setActivateCode(activateCode);

				
				

				 time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				 String sdate=time.format(new Date());
				 date=time.parse(sdate);
				stu.setLastTime(date);//淇濆瓨涓婃鐧诲綍鏃堕棿
				
				if(studentDao.save(stu)){		
					ActionContext.getContext().getSession().put("studentId",getEmail());

					//ActionContext.getContext().getSession().put("lastlogintime", stu.getLastTime().toString().substring(0,19));//淇濆瓨涓婃鐧诲綍鏃堕棿

					ActionContext.getContext().getSession().put("lastlogintime", sdate);//淇濆瓨涓婃鐧诲綍鏃堕棿

					ActionContext.getContext().getSession().put("usertype", "student");
					HttpServletRequest requestTemp = ServletActionContext.getRequest();
					String path = requestTemp.getContextPath();
					String basePath = requestTemp.getScheme()+"://"+requestTemp.getServerName()+":"+requestTemp.getServerPort()+path+"/";
					
					String type = "student";
					SendEmail.sendEmailToActivate(email, basePath, activateCode, type);
					
					return "register_success_student";	//濉啓涓汉淇℃伅椤甸潰
					//return "success_student";
				}else
					return "failure";			
			//StudentDao.merge(student);
			}catch(Exception e){
				
				e.printStackTrace();
				return "failure";
			}
		}else if(getUsertype()!= null && getUsertype().equals("2")){//老师
			Teacher teacher = new Teacher(getEmail(),getPassword());
			
			try{			
				SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");			

				//teacher.setRegisterTime(new Date());//淇濆瓨娉ㄥ唽鏃堕棿


				Date date = time.parse(time.format(new Date()));
				teacher.setRegisterTime(date);//淇濆瓨娉ㄥ唽鏃堕棿
				

				time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				//teacher.setLastTime(new Date());//淇濆瓨涓婃鐧诲綍鏃堕棿
				String activateCode = getRandomString();
				teacher.setActivateCode(activateCode);

				 String sdate=time.format(new Date());
				date = time.parse(sdate);
				teacher.setLastTime(date);//淇濆瓨涓婃鐧诲綍鏃堕棿
				

				if(teacherDao.save(teacher)){

					//ActionContext.getContext().getSession().put("lastlogintime", teacher.getLastTime().toString().substring(0,19));//淇濆瓨涓婃鐧诲綍鏃堕棿

					ActionContext.getContext().getSession().put("lastlogintime", sdate);//淇濆瓨涓婃鐧诲綍鏃堕棿

					ActionContext.getContext().getSession().put("teacherId",getEmail());
					ActionContext.getContext().getSession().put("usertype", "teacher");
					
					
					HttpServletRequest requestTemp = ServletActionContext.getRequest();
					String path = requestTemp.getContextPath();
					String basePath = requestTemp.getScheme()+"://"+requestTemp.getServerName()+":"+requestTemp.getServerPort()+path+"/";
					String type = "teacher";
					SendEmail.sendEmailToActivate(email, basePath, activateCode, type);
					
					//return "success_teacher";
					return "register_success_teacher"; //璺冲埌濉啓涓汉淇℃伅椤甸潰
				}else
					return "failure";			
			//StudentDao.merge(student);
			}catch(Exception e){
				return "failure";
			}
		}else
			return "faliure";
		
	}
	public String activateStudentOrTeacher() {
		if(usertype.equals("student")) {
			
			Student student = studentDao.findById(email);
			if(activateCode.equals(student.getActivateCode())) {
				student.setActivateCode("0");
				studentDao.update(student);
			}
			return "activeSuccess";
		} else if(usertype.equals("teacher")) {
			Teacher teacher = teacherDao.findById(email);
			if(activateCode.equals(teacher.getActivateCode())) {
				teacher.setActivateCode("0");
				teacherDao.update(teacher);
			}
			return "activeSuccess";
		} else {
			return "failure";
		}
	
	}
	public String getUsertype() {
		return usertype;
	}

	public void setUsertype(String usertype) {
		this.usertype = usertype;
	}

	

	
	public StudentDao getStudentDao() {
		return studentDao;
	}

	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}

	public TeacherDao getTeacherDao() {
		return teacherDao;
	}

	public void setTeacherDao(TeacherDao teacherDao) {
		this.teacherDao = teacherDao;
	}

	/**
	 * 姝ゅ鐢ㄤ簬鐢熸垚闅忔満8浣嶇殑婵�椿鐮�
	 * 鍦ㄦ敞鍐岀殑鏃跺�瀛樺偍鍒版暟鎹簱
	 * 涓�苟闅忛偖浠跺彂閫佸埌閭
	 * @return
	 */
	public String getRandomString() {
		Random random = new Random();
		String sRand = "";
		for (int i = 0; i < 8; i++) {
			String rand = getRandChar(random.nextInt(36));
			sRand = sRand + rand;
		}
		return sRand;
	}
	private String getRandChar(int randNumber) {
		return CHARARRAY[randNumber];
	}
	//鐢熸垚婵�椿鐮佺殑鏃跺�鍦ㄨ繖閲屽彇鍊�
	private static final String CHARARRAY[] = { "0", "1", "2", "3", "4", "5",
		"6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i",
		"j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
		"w", "x", "y", "z" };
	
}
